package com.gzsxy.sso.core.config;


import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;



/**
 * @author xiaolong
 * @version 1.0
 * @description: 过滤器的设置
 * @date 2021/10/19 8:42
 */
@Configuration
public class AuthFilterConfig {





    //通过方法完成对Filter组件的注册
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        //定义自己的过滤器
        registrationBean.setFilter(new MyFilter());
        //因为filter比bean先加载，也就是spring会先加载filter指定的类到container中，这样filter中注入的spring bean就为null了。
        //指明作用于filter的所有生命周期。为True，则spring来管理Filter.init()和Filter.destroy()；若为false，则这两个方法失效！！
        registrationBean.addInitParameter("targetFilterLifecycle", "true");

        registrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico");
        //配置过滤规则
        registrationBean.addUrlPatterns("/*");
        //request
        registrationBean.setDispatcherTypes(DispatcherType.REQUEST);
        return registrationBean;
    }


}

//实现过滤器
@AllArgsConstructor
class MyFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger("api_log");



    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    //拦截的方法都会进入dofilter方法
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        //这里填写你允许进行跨域的主机ip
        httpResponse.setHeader("Access-Control-Allow-Origin","*");
        //允许的访问方法
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        //用于CORS相关配置的缓存
        httpResponse.setHeader("Access-Control-Max-Age","3600");
        httpResponse.setHeader("Access-Control-Allow-Headers","*");

        //OPIIONS请求直接返回（前端跨域请求时，会发生两次请求，第一次OPIIONS测试服务器，第二次才是真正的post和get请求）
        //必须在第一次OPIIONS请求设置相应状态，不然无法进行第二次真正的请求
        if (httpRequest.getMethod().equals("OPTIONS")){
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        chain.doFilter(request, response);
    }
}
